package com.ou.csbs.capstone.tools;

import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.render.BasicShapeAttributes;
import gov.nasa.worldwind.render.Material;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.SwingUtilities;

import com.ou.csbs.capstone.models.RenderableModel;
import com.ou.csbs.capstone.models.shapes.Line;
import com.ou.csbs.capstone.views.worldwind.WorldWindCanvas;

/**
 * This is the FreehandDrawingTool. On a mouse click, the freehand drawing tool instances a Line object. Every 100 ms, if and only if the mouse has been dragged (to prevent a bunch of points being drawn at
 * the same location when the mouse button is held down but not drawing), it will add a new position to the Line's position list.
 * On mouse release, the object is finalized and drawn with the current set of attributes defined in the Attribute model.
 * 
 * @author Senior Capstone
 */
public class FreehandDrawingTool extends MouseAdapter{
	private Line tempLine;
	private ArrayList<Position> positions;
	private RenderableModel model;
	private BasicShapeAttributes creationAttributes;
	private long previousTime;

	public FreehandDrawingTool(RenderableModel model){
		this.model = model;
		positions = new ArrayList<Position>();
		this.creationAttributes = new BasicShapeAttributes();
		this.creationAttributes.setOutlineWidth(3);
		this.creationAttributes.setDrawInterior(false);
		this.creationAttributes.setOutlineMaterial(Material.BLACK);
		this.previousTime = System.currentTimeMillis();
	}

	@Override
	public void mousePressed(MouseEvent mouseEvent) {
		if(mouseEvent.getButton() == MouseEvent.BUTTON1){
			Position position = WorldWindCanvas.getWorldWindow().getCurrentPosition();
			if(position != null){
				tempLine = new Line(this.creationAttributes, this.positions);
				tempLine.drawShape(this.model);
			}
		}
		mouseEvent.consume();
	}
	@Override
	public void mouseDragged(MouseEvent mouseEvent){
		if(SwingUtilities.isLeftMouseButton(mouseEvent)){
			Position position = WorldWindCanvas.getWorldWindow().getCurrentPosition();
			//only add a point every .1 seconds (otherwise, you end up with a heck of a lot of points)
			if(position != null && tempLine != null && System.currentTimeMillis() - previousTime > 100){
				previousTime = System.currentTimeMillis();
				positions.add(position);
				tempLine.addPosition(position);
			}
		}
		mouseEvent.consume();
	}
	@Override
	public void mouseReleased(MouseEvent mouseEvent) {
		if(mouseEvent.getButton() == MouseEvent.BUTTON1){
			if(tempLine != null){
				tempLine.removeShape(this.model);
				tempLine = null;
				Line drawnLine = new Line(this.positions);
				drawnLine.drawShape(this.model);
				this.positions.clear();
			}
		}
		mouseEvent.consume();

	}
}
